package tom.vertx.core.demo09;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;

/**
 * UDP组播, 组播地址不知道写啥，没测试通过
 *
 * 组播：https://www.cnblogs.com/ricksteves/p/9702598.html
 * @author ZHUFEIFEI
 */
public class UDPMulticastDemo {

  public static void main(String[] args) {
    Vertx.vertx().deployVerticle(new Sender());
    Vertx.vertx().deployVerticle(new Receiver());
  }

  static class Sender extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {

      DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions());

      vertx.setPeriodic(2000L, id -> {
        Buffer buffer = Buffer.buffer("content");
        // Send a Buffer
        socket.send(buffer, 1234, "230.0.0.1", asyncResult -> {
          System.out.println("Send succeeded? " + asyncResult.succeeded());
        });
      });

      startPromise.complete();
    }
  }

  static class Receiver extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {
      DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions());
      socket.listen(1234, "0.0.0.0", asyncResult -> {
        if (asyncResult.succeeded()) {
          System.out.println("Listen on 1234");
          socket.handler(packet -> {
            System.out.println("receive package => " + packet.data().toString());
          });

          socket.listenMulticastGroup("230.0.0.1", asyncResult2 -> {
            if (asyncResult2.succeeded()) {
              System.out.println("Listen Multicast group");
              asyncResult2.result().handler(packet -> {
                System.out.println("receive group package => " + packet.data().toString());
              });
            } else {
              System.out.println("Listen Multicast failed" + asyncResult2.cause());
            }
          });
        } else {
          System.out.println("Listen failed" + asyncResult.cause());
        }
      });

      startPromise.complete();
    }
  }
}
